package com.guigu.user.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guigu.tms.exception.TmsException;
import com.guigu.tms.result.PageResult;
import com.guigu.tms.result.R;
import com.guigu.tms.result.ResultCode;
import com.guigu.user.entity.AddressBook;
import com.guigu.user.entity.Area;
import com.guigu.user.entity.City;
import com.guigu.user.entity.Province;
import com.guigu.user.entity.dto.AddressBookDTO;
import com.guigu.user.entity.query.AddressBookQuery;
import com.guigu.user.entity.vo.AddressBookVO;
import com.guigu.user.service.AddressBookService;
import com.guigu.user.service.AreaService;
import com.guigu.user.service.CityService;
import com.guigu.user.service.ProvinceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 地址簿 前端控制器
 * </p>
 *
 * @author TaoLong
 * @since 2021-11-09
 */
@RestController
@RequestMapping("/user/address-book")
@Api(tags = "地址簿管理")
@Transactional
@CacheConfig(cacheNames = "addressBook")
@Slf4j
public class AddressBookController {
    @Autowired
    private AddressBookService bookService;
    @Autowired
    private ProvinceService provinceService;
    @Autowired
    private CityService cityService;
    @Autowired
    private AreaService areaService;


    @ApiOperation(value = "查询地址簿信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码"),
            @ApiImplicitParam(name = "pageSize", value = "每页数量"),
            @ApiImplicitParam(name = "addressBookQuery", value = "查询对象")
    })
    @PostMapping("queryByNameOrPhoneOrCompanyNameOfPage/{pageNum}/{pageSize}")
    public PageResult<List<AddressBookVO>> queryByNameOrPhoneOrCompanyNameOfPage(
            @PathVariable String pageNum,
            @PathVariable String pageSize,
            @RequestBody AddressBookQuery addressBookQuery) {

        if (StringUtils.isBlank(pageSize) || !StringUtils.isNumeric(pageSize)) {
            pageSize = "5";
        }
        if (StringUtils.isBlank(pageNum) || !StringUtils.isNumeric(pageNum)) {
            pageNum = "1";
        }
        PageResult<List<AddressBookVO>> r = bookService.queryByNameOrPhoneOrCompanyName(addressBookQuery, Integer.parseInt(pageSize), Integer.parseInt(pageNum));
        return r;
    }


    @ApiOperation("添加地址薄信息")
    @ApiImplicitParam(name = "addressBookDTO", value = "添加地址薄信息对象")
    @PostMapping("/")
    @CacheEvict(allEntries = true)
    public R save(@RequestBody AddressBookDTO addressBookDTO) {
        if (ObjectUtils.isEmpty(addressBookDTO)) {
            throw new TmsException(ResultCode.ERROR_CODE, "参数addressBook为null");
        }
        /**
         * 判断是否通过审核
         */
        bookService.checkAndReview(addressBookDTO.getUserId());
        /**
         * 先将这些数据添加后主键回填之后,在进行添加地址表
         */
        AddressBook addressBook = new AddressBook();
        BeanUtil.copyProperties(addressBookDTO, addressBook);
        addressBook.setCreateTime(new Date());
        addressBook.setIsDefault(false);
        boolean b = bookService.save(addressBook);
        return b ? new R(ResultCode.SUCCESS_CODE, "添加地址薄成功!", true) : new R(ResultCode.ERROR_CODE, "添加地址簿失败!", false);
    }

    @ApiOperation("修改地址薄信息")
    @ApiImplicitParam(name = "addressBookDTO", value = "修改地址簿信息对象")
    @PutMapping("/")
    @CacheEvict(allEntries = true)
    public R update(@RequestBody AddressBookDTO addressBookDTO) {
        log.error("数据为===",addressBookDTO);
        if (ObjectUtils.isEmpty(addressBookDTO)) {
            throw new TmsException(ResultCode.ERROR_CODE, "参数addressBook为null");
        }
        bookService.checkAndReview(addressBookDTO.getUserId());
        AddressBook addressBook = new AddressBook();
        /**
         * 将属性复制进去进行修改
         */
        BeanUtil.copyProperties(addressBookDTO, addressBook);
        /**
         * 修改
         */
        bookService.updateById(addressBook);
        return new R(ResultCode.SUCCESS_CODE, "修改地址薄成功!", true);
    }


    @ApiOperation("删除地址薄信息")
    @ApiImplicitParam(name = "id", value = "删除地址簿信息Id")
    @DeleteMapping("/{id}")
    @CacheEvict(allEntries = true)
    public R delete(@PathVariable String id) {
        if (StringUtils.isBlank(id)) {
            throw new TmsException(ResultCode.ERROR_CODE, "参数id为null");
        }
        /**
         * 删除之前先查找出它所对应的地址表,先把那里删了之后,在删除地址簿信息
         */
        AddressBook book = bookService.getById(id);
        /**
         * 查找出book对象后,根据所对应的id进行对应的删除处理
         */
        provinceService.removeById(String.valueOf(book.getProvinceId()));
        cityService.removeById(String.valueOf(book.getCityId()));
        areaService.removeById(String.valueOf(book.getCountyId()));
        /**
         * 删除之后在删除地址簿信息
         */
        boolean b = bookService.removeById(id);
        return b ? new R(ResultCode.SUCCESS_CODE, "删除地址薄成功!", true) : new R(ResultCode.ERROR_CODE, "删除地址簿失败!", false);
    }


    @ApiOperation("查询地址薄信息")
    @ApiImplicitParam(name = "id", value = "查询地址簿信息Id")
    @GetMapping("/{id}")
    @Cacheable(key = "#id")
    public R queryById(@PathVariable String id) {
        if (StringUtils.isBlank(id)) {
            throw new TmsException(ResultCode.ERROR_CODE, "参数id为null");
        }
        /**
         * 获取地址簿信息
         */
        AddressBook book = bookService.getById(id);
        AddressBookVO addressBookVO = new AddressBookVO();
        /**
         * 将这些获取的数据复制到addressBookVO中
         */
        BeanUtil.copyProperties(book, addressBookVO);
        log.error("结果为==",addressBookVO);
        return new R(ResultCode.SUCCESS_CODE, addressBookVO);
    }


    @ApiOperation("修改地址薄信息为默认地址")
    @ApiImplicitParam(name = "addressBookVO", value = "地址薄信息对象")
    @PutMapping("/changeTheDefaultAddress")
    public R changeTheDefaultAddress(@RequestBody AddressBookVO addressBookVO) {
        R r = bookService.changeTheDefaultAddress(addressBookVO);
        return r;
    }


    @ApiOperation("根据用户id查询所对应的地址信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "query", value = "查询对象"),
            @ApiImplicitParam(name = "pageSize", value = "页数"),
            @ApiImplicitParam(name = "pageNum", value = "页码")
    })
    @PostMapping("/queryAddressBookBasedOnUserId/{pageSize}/{pageNum}")
    public R<Page<AddressBookVO>> queryAddressBookBasedOnUserId(@RequestBody AddressBookQuery query,
                                                                @PathVariable String pageSize,
                                                                @PathVariable String pageNum) {
        if (StringUtils.isBlank(pageSize) || !StringUtils.isNumeric(pageSize)) {
            pageSize = "5";
        }
        if (StringUtils.isBlank(pageNum) || !StringUtils.isNumeric(pageNum)) {
            pageNum = "1";
        }
        return bookService.queryAddressBookBasedOnUserId(query, Integer.parseInt(pageSize), Integer.parseInt(pageNum));
    }
}

